package org.itzixi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.itzixi.api.feign.FileMicroServiceFeign;
import org.itzixi.base.BaseInfoProperties;
import org.itzixi.enums.Sex;
import org.itzixi.mapper.UsersMapper;
import org.itzixi.pojo.Users;
import org.itzixi.service.UsersService;
import org.itzixi.service.UsersService;
import org.itzixi.utils.DesensitizationUtil;
import org.itzixi.utils.LocalDateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>

 */
@Service
public class UsersServiceImpl extends BaseInfoProperties implements UsersService {
    @Resource
    private FileMicroServiceFeign fileMicroServiceFeign;
    private final static String USER_FACE1="";
    @Resource
    private UsersMapper usersMapper;
    @Override
    public Users queryMobileIsExist(String mobile) {
        return usersMapper.selectOne(
                new QueryWrapper<Users>()
                        .eq("mobile",mobile)
        );
    }

    @Transactional
    @Override
    public Users createUsers(String mobile, String nickname) {
        Users user=new Users();
        //设置手机号
        user.setMobile(mobile);
        String uuid= UUID.randomUUID().toString();
        String uuidStr[]=uuid.split("-");

        //设置微信号
        String wechatNum="wx"+uuidStr[0]+uuidStr[1];
        user.setWechatNum(wechatNum);

        //设置微信二维码
        String wechatNumUrl = getQrCodeUrl(wechatNum, TEMP_STRING);
        user.setWechatNumImg(wechatNumUrl);

        //设置用户昵称
        if(nickname==null || nickname.trim().length()==0){
            String DesensitizationMobile= DesensitizationUtil.commonDisplay(mobile);
            nickname="用户"+DesensitizationMobile;
        }
        user.setNickname(nickname);

        //设置其他默认值
        user.setRealName("");
        user.setSex(Sex.secret.type);
        user.setFace(USER_FACE1);
        user.setFriendCircleBg(USER_FACE1);
        user.setEmail("");
        user.setBirthday(LocalDateUtils
                .parseLocalDate("1980-01-01",
                        LocalDateUtils.DATE_PATTERN));
        user.setCountry("中国");
        user.setProvince("");
        user.setCity("");
        user.setDistrict("");
        user.setCreatedTime(LocalDateTime.now());
        user.setUpdatedTime(LocalDateTime.now());
        usersMapper.insert(user);
        return user;
    }

    private String getQrCodeUrl(String wechatNumber, String userId){
        try {
            return fileMicroServiceFeign.generatorQrCode(wechatNumber,userId);
        } catch (Exception e) {
//            throw new RuntimeException(e);
            return null;
        }
    }
}
